import tkinter as tk
from tkinter import messagebox
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from tkinter import filedialog, StringVar, IntVar, BooleanVar, DoubleVar
from data.Database import Subject
from ui.panel import SubjectTree
import json
import os


class MainWindow(ttk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.master = master
        self.pack(fill=BOTH, expand=YES)
        # 程序变量定义
        self.file_name = StringVar(value='还没有选择文件.....')
        self.ana = {
            'zero': IntVar(value=1),
            'rank': IntVar(value=1),
            'distribute': IntVar(value=1),
            'max': IntVar(value=1),
            'min': IntVar(value=1),
            'mean': IntVar(value=1),
            'excellent': IntVar(value=1),
            'pass': IntVar(value=1),
            'std': IntVar(value=1),
            'inclusion_single': IntVar(value=1),
            'inclusion_all': IntVar(value=1),
            'task': IntVar(value=300),
            'good_line': DoubleVar(value=0.2),
            'low_line': DoubleVar(value=0.7),
            'score_cut': IntVar(value=5),
            'rsr': IntVar(value=1)
        }
        self.ana_set()
        # 程序界面初始化
        self.init_menu()
        self.init_theme()
        self.init_setting()

    def init_menu(self):
        self.menubar = tk.Menu(self)
        self.master.config(menu=self.menubar)
        file_menu = tk.Menu(self.menubar, tearoff=0)
        file_menu.add_command(label="打开文件", command=self.open_file)
        file_menu.add_separator()
        file_menu.add_command(label="退出系统", command=self.quit)
        self.menubar.add_cascade(label="文件", menu=file_menu)

        help_menu = tk.Menu(self.menubar, tearoff=0)
        help_menu.add_command(label='使用说明', command=self.help)
        self.menubar.add_cascade(label='帮助', menu=help_menu)

    def init_theme(self):
        # 主题配置
        self.style = ttk.Style()
        self.theme_names = self.style.theme_names()
        # self.label = ttk.Label(self, text="xxxx").pack()
        # 头部主题区域
        self.theme_selection = ttk.Frame(self, padding=(10, 30, 10, 30))
        self.theme_selection.pack(fill=X)
        self.theme_selected = ttk.Label(master=self.theme_selection, text='七彩阳光成绩分析工具', font="-size 30 -weight bold", anchor=CENTER)
        self.theme_selected.pack(side=LEFT, expand=YES, fill=BOTH)
        self.lbl = ttk.Label(self.theme_selection, text="选择主题：")
        self.theme_cbo = ttk.Combobox( master=self.theme_selection, values=self.theme_names,)
        self.theme_cbo.bind("<<ComboboxSelected>>", self.change_theme)
        self.theme_cbo.pack(padx=10, side=RIGHT)
        self.theme_cbo.current(self.theme_names.index(self.style.theme.name))
        self.lbl.pack(side=RIGHT)

    def init_setting(self):
        # 中间分析设置总面板
        self.setting_frame = ttk.Frame(self)
        self.setting_frame.pack(fill=BOTH, expand=True)
        # 左边分析项目设置面板
        self.left = ttk.Frame(self.setting_frame, padding=5, width=400)
        self.left.pack(side=LEFT, fill=BOTH, expand=YES)
        # 文件选择
        file_frame = ttk.LabelFrame(master=self.left, text="文件", padding=5)
        file_frame.pack(side=TOP, fill=X)
        ttk.Button(file_frame, text='选择文件', command=self.open_file).pack(side=LEFT)
        ttk.Label(master=file_frame, text='还没有选择文件.....', anchor=W, padding=(5, 0, 0, 0), width=30,
                  textvariable=self.file_name).pack(side=LEFT, fill=X, expand=True)
        # 总体分析
        rb_group_total = ttk.Labelframe(master=self.left, text="总体", padding=5)
        rb_group_total.pack(fill=X, pady=10, side=TOP)
        ttk.Checkbutton(rb_group_total, text="去除0分", variable=self.ana['zero']).pack(side=LEFT, padx=5)
        ttk.Checkbutton(rb_group_total, text="名次", variable=self.ana['rank']).pack(side=LEFT, padx=5)
        ttk.Checkbutton(rb_group_total, text="分布", variable=self.ana['distribute']).pack(side=LEFT, padx=5)

        # 统计设置
        rb_group_total = ttk.Labelframe(master=self.left, text="统计设置", padding=5)
        rb_group_total.pack(fill=BOTH, pady=10, side=TOP, expand=YES)

        ttk.Checkbutton(rb_group_total, text="最高分", variable=self.ana['max']).grid(row=0, column=0, padx=10, pady=10)
        ttk.Checkbutton(rb_group_total, text="最低分", variable=self.ana['min']).grid(row=0, column=1, padx=10)
        ttk.Checkbutton(rb_group_total, text="平均分", variable=self.ana['mean']).grid(row=0, column=2, padx=10)
        ttk.Checkbutton(rb_group_total, text="优秀率", variable=self.ana['excellent']).grid(row=0, column=3, padx=10, pady=10)
        ttk.Checkbutton(rb_group_total, text="及格率", variable=self.ana['pass']).grid(row=1, column=0, padx=10)
        ttk.Checkbutton(rb_group_total, text="标准差", variable=self.ana['std']).grid(row=1, column=1, padx=10, pady=10)
        ttk.Checkbutton(rb_group_total, text="达标数", variable=self.ana['inclusion_single']).grid(row=1, column=2, padx=10)
        ttk.Checkbutton(rb_group_total, text="有效达标", variable=self.ana['inclusion_all']).grid(row=1, column=3, padx=10)

        rb_zb_group = ttk.Labelframe(master=self.left, text='参数设置', padding=10)
        rb_zb_group.pack(fill=BOTH, pady=10, side=TOP, expand=YES)
        ttk.Label(master=rb_zb_group, text='指标数: ').grid(row=0, column=0)
        ttk.Spinbox(master=rb_zb_group, from_=0, to=3000, textvariable=self.ana['task']).grid(row=0, column=1)
        ttk.Label(master=rb_zb_group, text='*上线期望值').grid(row=0, column=2, sticky=W)

        ttk.Label(master=rb_zb_group, text='优秀线: ').grid(row=1, column=0)
        ttk.Spinbox(master=rb_zb_group, from_=0, to=1, increment=0.1, textvariable=self.ana['good_line']).grid(row=1, column=1)
        ttk.Label(master=rb_zb_group, text='*优秀比例取值0-0.5').grid(row=1, column=2, sticky=W)

        ttk.Label(master=rb_zb_group, text='低分线: ').grid(row=2, column=0)
        ttk.Spinbox(master=rb_zb_group, from_=0, to=1, increment=0.1, textvariable=self.ana['low_line']).grid(row=2, column=1)
        ttk.Label(master=rb_zb_group, text='*低分线，取值0.5-1').grid(row=2, column=2, sticky=W)

        ttk.Label(master=rb_zb_group, text='分数段: ').grid(row=3, column=0)
        ttk.Spinbox(master=rb_zb_group, from_=0, to=150, textvariable=self.ana['score_cut']).grid(row=3, column=1)
        ttk.Label(master=rb_zb_group, text='*分数分布分析').grid(row=3, column=2, sticky=W)

        score_group = ttk.Labelframe(master=self.left, text='得分计算', padding=5)
        score_group.pack(fill=BOTH, pady=1, side=TOP, expand=YES)
        ttk.Checkbutton(score_group, text="RSR", variable=self.ana['rsr']).pack(side=LEFT, fill=X)
        ttk.Button(self.left, text="生成分析结果", command=self.calculate).pack(side=TOP, expand=YES, fill=X, pady=10)

        # 右侧科目设置面板
        self.right = SubjectTree(self.setting_frame, padding=5, width=400)
        self.right.pack(side='left', fill=BOTH, expand=True)

    def change_theme(self, e):
        # t = self.cbo.get()
        t = self.theme_cbo.get()
        self.style.theme_use(t)
        # self.theme_selected.configure(text=t)
        # self.theme_cbo.selection_clear()
        # self.default.focus_set()

    def ana_get(self):
        ret = dict()
        for k, v in self.ana.items():
            ret[k] = v.get()
        # print(ret)
        return ret

    def ana_set(self):
        if not os.path.exists('config.ini'):
            with open("config.ini", "w") as file:
                pass

        with open("config.ini", 'r+') as file:
            content = file.read()
            if content:
                ana = json.loads(content)
                # print("set ana!")
                for k, v in ana.items():
                    # print(k, "=", v)
                    self.ana[k].set(v)
                # print(self.ana)

    def open_file(self):
        # 此处保存设置
        with open("config.ini", "w") as file:
            config = json.dumps(self.ana_get())
            file.write(config)
        file_path = filedialog.askopenfilename(filetypes=(("Files", "*.xls *.xlsx"),))
        self.file_name.set(file_path)
        self.ana_set()
        # self.file = file_path

    def calculate(self):
        pass

    def help(self):
        messagebox.showinfo("使用说明", "<a>使用说明</a>")



if __name__ == '__main__':
    root = tk.Tk()
    root.geometry("900x800+500+500")
    window = MainWindow(root)
    root.mainloop()

